package com.chenxiao.mybatisplus.mq;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: CX
 * @Date: Created in  2023/03/11 17:09
 * @version: v1.0
 * @Description: TODO
 * rabbitmq 消息生产端
 **/
@Service
public class RabbitmqProvider {
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Value("${rabbitConfig.exchageName}")
    private String exchageName;
    @Value("${rabbitConfig.directRoutingName}")
    private String routingName;

    @PostMapping("/sendDirectMessage")
    @ApiModelProperty("发送消息")
    public void sendDirectMessage() {
        String messageId = String.valueOf(UUID.randomUUID());
        String messageData = "test message, hello!";
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Map<String,Object> map=new HashMap<>();
        map.put("messageId",messageId);
        map.put("messageData",messageData);
        map.put("createTime",createTime);
        map.put("name","天气热了，孔乙己脱下长衫");
        map.put("posName","混凝土瞬间移动师");
        map.put("joblevelName","高级混凝土瞬间移动师");
        map.put("departmentName","啊Q攻作室");

        //将消息携带绑定键值：TestDirectRouting 发送到交换机TestDirectExchange
        confirmCallBackMethod(exchageName, routingName, map);
        // rabbitTemplate.getMessageConverter();
    }

    /**
     * mq 生产者入库
     * @param message
     */
    public void doPostMqMethod(Object message){
        confirmCallBackMethod("OrderExchange", "OrderRouting", message);
    }

    private void confirmCallBackMethod(String exchageName, String routingName, Object message) {
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if(ack)
                System.out.println("触发confirm回调函数,交换机接受到了");
            else{
                System.out.println("触发confirm回调函数,交换机收不到信息,原因:"+cause);
                assert correlationData != null;
                System.out.println("消息对应的的CorrelationData id:"+correlationData.getId());
            }
        });
        rabbitTemplate.convertAndSend(exchageName, routingName, message);
    }
}
